<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title || pTitle"
    :width="width"
  >
    <v-form-render
      :form-json="formJson"
      :form-data="keepData"
      :option-data="{}"
      ref="vForm"
    >
      <template v-for="item in slots" #[item]="{ formModel }">
        <slot :name="item" :form="formModel"></slot>
      </template>
    </v-form-render>
    <template #footer v-if="showButton">
      <span class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="onSubmit"> 确 认 </el-button>
      </span>
    </template>
    <slot></slot>
  </el-dialog>
</template>

<script setup>
import { reactive, defineProps, ref, defineEmits, nextTick } from "vue";
import defaultJson from "./default.json";
const { proxy } = getCurrentInstance();

const vForm = ref();
const props = defineProps({
  formJson: {
    type: Object,
    default: () => defaultJson,
  },
  title: {
    type: String,
  },
  slots: {
    type: Array,
    default: () => [],
  },
  showButton: {
    type: Boolean,
    default: true,
  },
  width: {
    type: String,
    default: "55%",
  },
});
const pTitle = computed(() => {
  if (keepData.value.id) {
    return "修改";
  } else {
    return "新增";
  }
});
const keepData = ref({});
const dialogFormVisible = ref(false);
const open = (data, json) => {
  dialogFormVisible.value = true;
  keepData.value = JSON.parse(JSON.stringify(data));
  nextTick().then(async () => {
    setFormData({});
    await setFormJson(json);

    setTimeout(() => {
      setFormData(data);
    }, 135);
  });
};
const close = () => {
  dialogFormVisible.value = false;
};
const emits = defineEmits(["onSubmit", "onChange"]);

const setFormJson = async (json) => {
  await vForm.value.setFormJson(json);
};
const setFormData = (data) => {
  vForm.value.setFormData(data);
};

const onSubmit = async () => {
  try {
    const formData = await vForm.value.getFormData();
    if (formData) {
      emits("onSubmit", { ...keepData.value, ...formData });
      close();
    } else {
      proxy.$modal.msgError("有必填项未填写");
    }
    return formData;
  } catch (error) {
    proxy.$modal.msgError("有必填项未填写");
    return false;
  }
};
defineExpose({
  setFormJson,
  setFormData,
  onSubmit,
  open,
  close,
});
</script>

<style lang="scss" scoped></style>
